package com.yonghui.springsecurityoauth2demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CustomAuthController {


    @GetMapping("/oauth/login")
    public String loginPage(Model model){
        //返回跳转页面
        return "oauth-login";
    }

    @GetMapping("/custom/login")
    public String getCustomLoginPage(Model model, HttpServletRequest request) {
        // 从 session 中获取错误信息
        String errorMessage = (String) request.getSession().getAttribute("errorMessage");
        if (errorMessage != null) {
            model.addAttribute("errorMessage", errorMessage);
            request.getSession().removeAttribute("errorMessage"); // 显示后删除错误信息
        }

        // 从Session中获取OAuth2参数并添加到Model中
        String[] params = {"client_id", "response_type", "redirect_uri", "scope", "state"};
        for (String param : params) {
            //String value = request.getParameter(param);
            String value = (String) request.getSession().getAttribute(param);
            if (!StringUtils.isEmpty(value)) {
                model.addAttribute(param, value);
            }
        }

        return "login"; // 返回登录页面
    }

    @RequestMapping("/custom/confirm_access")
    public String processAuthorization(Model model, HttpServletRequest request) {
        // 从请求参数中获取 OAuth2 参数，并添加到 Model 中
        model.addAttribute("client_id", request.getParameter("client_id"));
        model.addAttribute("response_type", request.getParameter("response_type"));
        model.addAttribute("redirect_uri", request.getParameter("redirect_uri"));
        model.addAttribute("scope", request.getParameter("scope"));
        //model.addAttribute("state", request.getParameter("state"));

        return "custom_confirm_access";
    }


    @GetMapping("/oauth/error")
    public String error(Model model){
        return "oauth-error";
    }
}
